package edu.drexel.info636.assignments.controllers;

import java.util.ArrayList;

import org.springframework.stereotype.Component;

import edu.drexel.info636.assignments.models.Record;

/**
 * Handles all record (list of sets of numbers) events.
 * 
 * @author Chase Miller
 *
 */
@Component
public class RecordController extends ControllerBase {

    /**
     * Gets a record item from the user and returns the object representation.
     * 
     * @return - a RecordItem.
     */
    public Record getRecordItemFromUser() {
	Record itemToReturn;

	System.out.println("Create a new record...");
	System.out.println("Be sure to enter the first number as the same type as the others in the data set (i.e. as x) and the second in the same way (i.e. y).");

	ArrayList<Double> userNumbers = new ArrayList<Double>();

	for (int i = 0; i < Record.getMaxNumberssInRecord(); i++) {
	    System.out.println("Getting item " + (i + 1) + " of " + Record.getMaxNumberssInRecord() + "...");
	    Double next = this.getNewNumberFromUser();

	    try {
		userNumbers.add(next);
	    } catch (Throwable t) {
		System.out.println("There was an error adding your number.  Ignoring...");
	    }
	}

	itemToReturn = new Record(userNumbers);

	System.out.println("New record created");

	return itemToReturn;
    }

    /**
     * Prompts the user whether they want to modify this record item.
     * 
     * @param itemToModify
     * @return
     */
    public Record modifyRecordItem(Record itemToModify) {
	Record newRecord = new Record();

	System.out.println("Starting single record modification...");
	System.out.println(itemToModify);

	Boolean acceptRemaining = false;

	for (Double nextNumber : itemToModify.getNumberSet()) {
	    if (acceptRemaining) {
		newRecord.getNumberSet().add(nextNumber);
	    } else {
		/* Get the initial action (a/r/d) */
		// For deleting we'll do nothing (and not add it to the new
		// list).
		String actionChoice = this.getModifyAction(nextNumber);

		if (actionChoice.equals("a")) {
		    newRecord.addNumber(nextNumber);

		} else if (actionChoice.equals("r")) {
		    newRecord.addNumber(this.getNewNumberFromUser());
		}

		acceptRemaining = this.genericBooleanPromptAndResponse("Would you like to accept all remaining numbers in this record (y/n)?");
	    }
	}

	System.out.println("Record modification complete \n\n");

	return newRecord;
    }

    /**
     * Prompts and gets a valid modify action from the user.
     * 
     * @return
     */
    private String getModifyAction(Double number) {
	String result = null;

	while (result == null) {
	    System.out.println("The number is " + number + ". Would you like to (a) accept or (r) replace this number?  Enter the letter and press enter");
	    String userInput = this.scan.nextLine();

	    if (userInput.equalsIgnoreCase("a") || userInput.equalsIgnoreCase("r")) {
		result = userInput;
	    }
	}

	return result;
    }
}
